<?php
/**
 * Created by PhpStorm.
 * User: yunzhi.liu
 * Date: 2020/10/9
 * Time: 11:02
 */

namespace app\http\middleware;


class AliNotify
{
    public function handle($request, \Closure $next)
    {

        try{
            if(!$request->isPost()){
                throw new \Exception('请求类型错误');
            }
            // 返回信息
            $requestArr = $_POST;
            //file_put_contents('aliPayNotifyError.txt', '通知信息:' . json_encode($requestArr) . PHP_EOL, FILE_APPEND);


            $aliPayConfig = config('alipay');

            require '../extend/AlipaySDK/aop/AopClient.php';

            $aop = new \AopClient();
            $aop->alipayrsaPublicKey = $aliPayConfig['public_key'];
            // 验签
            $checkSign = $aop->rsaCheckV1($requestArr, null, $requestArr['sign_type']);
            if (!$checkSign) {
                throw new \Exception('验签失败');
            }

            // 验证商户号
            if ($requestArr['app_id'] != $aliPayConfig['app_id']) {
                throw new \Exception('商户号错误:' . $requestArr['app_id']);
            }

            // 支付未成功
            if ($requestArr['trade_status'] !== 'TRADE_SUCCESS') {
                throw new \Exception('支付状态不是支付成功:' . $requestArr['trade_status']);
            }

            $request->order_id = $requestArr['out_trade_no'];
            return $next($request);
        }catch(\Exception $exception){
            file_put_contents('aliPayNotifyError.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
            return error($exception->getMessage());
        }

    }
}